package com.ki.erp.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.util.Base64;
import java.util.Date;


public class JwtUtil {
    public static final Long DEFAULT_TIME = 1000L * 60 * 60 * 24;

    public static String generateToken(String userId, String base64Key) {
        return generateToken(userId, base64Key, DEFAULT_TIME);
    }

    public static String generateToken(String userId, String base64Key, Long effective) {
        byte[] signingKey = Base64.getDecoder().decode(base64Key);
        return Jwts.builder()
                .claim("userId", userId)
                .issuedAt(new Date())
                .expiration(new Date(new Date().getTime() + effective))
                .signWith(Keys.hmacShaKeyFor(base64Key.getBytes()))
                .compact();
    }


    public static String validateToken(String token, String base64Key) {
        return (String) Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(base64Key.getBytes()))
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .get("userId");
    }
}
